#!/bin/bash

# Hadoop 自动安装脚本（带下载进度条）
# 功能：自动安装 Java 和 Hadoop，并正确配置环境变量
# 适用系统：Ubuntu/Debian

set -e  # 遇到错误立即退出

# 配置参数
HADOOP_VERSION="3.3.5"
HADOOP_MIRROR="https://dlcdn.apache.org/hadoop/common"
HADOOP_URL="${HADOOP_MIRROR}/hadoop-${HADOOP_VERSION}/hadoop-${HADOOP_VERSION}.tar.gz"
INSTALL_DIR="/usr/local"
HADOOP_DIR="${INSTALL_DIR}/hadoop"
TEMP_DIR="/tmp/hadoop_install_$(date +%s)"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

# 打印带颜色的消息
function info() { echo -e "${GREEN}[INFO] $1${NC}"; }
function warn() { echo -e "${YELLOW}[WARN] $1${NC}"; }
function error() { echo -e "${RED}[ERROR] $1${NC}"; exit 1; }

# 检查并安装 Java
function install_java() {
    if ! command -v java &> /dev/null; then
        info "Java 未安装，开始安装 OpenJDK 8..."
        sudo apt-get update
        sudo apt-get install -y openjdk-8-jdk || error "Java 安装失败!"
        
        # 设置 JAVA_HOME
        JAVA_HOME=$(dirname $(dirname $(readlink -f $(which java))))
        info "Java 安装成功！JAVA_HOME: $JAVA_HOME"
    else
        JAVA_HOME=$(dirname $(dirname $(readlink -f $(which java))))
        info "Java 已安装: $(java -version 2>&1 | head -n 1)"
        info "检测到 JAVA_HOME: $JAVA_HOME"
    fi
}

# 安装 Hadoop（带进度条）
function install_hadoop() {
    info "创建临时目录: $TEMP_DIR"
    mkdir -p "${TEMP_DIR}"
    cd "${TEMP_DIR}" || error "无法进入临时目录"

    info "下载 Hadoop ${HADOOP_VERSION} (显示下载进度)..."
    echo "----------------------------------------"
    wget --show-progress -q "${HADOOP_URL}" -O "hadoop-${HADOOP_VERSION}.tar.gz" || error "Hadoop 下载失败"
    echo "----------------------------------------"

    info "解压 Hadoop..."
    tar -xzf "hadoop-${HADOOP_VERSION}.tar.gz"

    info "安装到 ${HADOOP_DIR}"
    sudo mv "hadoop-${HADOOP_VERSION}" "${HADOOP_DIR}" || error "移动 Hadoop 失败"
}

# 配置环境
function configure_env() {
    info "配置环境变量..."

    # 更新 .bashrc
    grep -q "HADOOP_HOME" ~/.bashrc || {
        echo -e "\n# Hadoop Environment Variables" >> ~/.bashrc
        echo "export JAVA_HOME=${JAVA_HOME}" >> ~/.bashrc
        echo "export HADOOP_HOME=${HADOOP_DIR}" >> ~/.bashrc
        echo 'export PATH=$PATH:$JAVA_HOME/bin:$HADOOP_HOME/bin:$HADOOP_HOME/sbin' >> ~/.bashrc
        echo "export HADOOP_CLASSPATH=\$(hadoop classpath)" >> ~/.bashrc
    }

    # 配置 hadoop-env.sh
    local HADOOP_ENV_FILE="${HADOOP_DIR}/etc/hadoop/hadoop-env.sh"
    sudo sed -i "/export JAVA_HOME=/c\export JAVA_HOME=${JAVA_HOME}" "${HADOOP_ENV_FILE}" || {
        warn "hadoop-env.sh 中没有找到 JAVA_HOME，手动添加..."
        echo "export JAVA_HOME=${JAVA_HOME}" | sudo tee -a "${HADOOP_ENV_FILE}" >/dev/null
    }

    # 设置权限
    sudo chown -R $(whoami): "${HADOOP_DIR}"
    sudo chmod +x "${HADOOP_DIR}/bin/"*
    sudo chmod +x "${HADOOP_DIR}/sbin/"*
}

# 清理安装
function cleanup() {
    info "清理临时文件..."
    cd ~
    rm -rf "${TEMP_DIR}"
}

# 验证安装
function verify_install() {
    info "验证安装..."
    
    echo -e "\nJava 版本:"
    java -version || error "Java 验证失败"
    
    echo -e "\nHadoop 版本:"
    "${HADOOP_DIR}/bin/hadoop" version || error "Hadoop 验证失败"
    
    echo -e "\n环境变量:"
    echo "JAVA_HOME: $JAVA_HOME"
    echo "HADOOP_HOME: $HADOOP_DIR"
    echo "PATH: $PATH"
}

# 主函数
function main() {
    info "开始 Hadoop 安装流程..."
    install_java
    install_hadoop
    configure_env
    cleanup
    verify_install
    
    info "安装成功完成！"
    echo -e "\n请运行以下命令使环境变量生效:"
    echo "source ~/.bashrc"
    echo -e "\n或重新打开终端窗口"
}

# 执行主函数
main